package com.yanq.liancar.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.google.zxing.Result;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.RxSPTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.ToastUtil;
import com.yanq.liancar.util.Utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DateTimePicker;

public class BindCarActivity extends BaseToolbarActivity {

    @BindView(R.id.tv_selectAddress)
    TextView tvSelectAddress;
    @BindView(R.id.tv_selectbrand)
    TextView tvSelectbrand;
    @BindView(R.id.tv_selectbrand_ll)
    RelativeLayout tvSelectbrandLl;
    @BindView(R.id.chexi)
    TextView chexi;
    @BindView(R.id.chexi_ll)
    RelativeLayout chexiLl;
    @BindView(R.id.chexing)
    TextView chexing;
    @BindView(R.id.chepai_time)
    TextView chepaiTime;
    @BindView(R.id.chexing_ll)
    RelativeLayout chexingLl;
    @BindView(R.id.bind_car_plate)
    EditText bindCarPlate;
    @BindView(R.id.bind_car_number)
    EditText bindCarNumber;
    @BindView(R.id.bind_car_engine)
    EditText bindCarEngine;
    @BindView(R.id.chepai_time_ll)
    RelativeLayout chepaiTimeLl;
    @BindView(R.id.bind_car_number_OBD)
    EditText bindCarNumberOBD;
    @BindView(R.id.bind_car_OBD_qrCode)
    ImageView bindCarOBDQrCode;
    @BindView(R.id.bind_car_ck)
    CheckBox bind_car_ck;
    @BindView(R.id.bind_car_commit_btn)
    TextView bindCarCommitBtn;
    private int moren = 0;
    private int pinpaiID,chexiID,chexingID;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //让布局向上移来显示软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_bind_car);
        ButterKnife.bind(this);
        mTvTitle.setText("添加绑定车辆");
        tvSelectAddress.setText(RxSPTool.getString(this, "SelectAddressTitle"));
        Utils.setStatusBar(this, true, false);


        bind_car_ck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    moren = 0;
                } else {
                    moren = 1;
                }
            }
        });

    }

    private void initEditTextHintColor() {
        SpannableString s1 = new SpannableString("请输入车牌号");
        SpannableString s2 = new SpannableString("请输入车架号码");
        SpannableString s3 = new SpannableString("请输入发动机号");
        AbsoluteSizeSpan textSize = new AbsoluteSizeSpan(14, true);
        s1.setSpan(textSize, 0, s1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        s2.setSpan(textSize, 0, s1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        s3.setSpan(textSize, 0, s1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        bindCarPlate.setHint(s1);
        bindCarNumber.setHint(s2);
        bindCarEngine.setHint(s3);
    }

    @OnClick({R.id.bind_car_OBD_qrCode, R.id.bind_car_commit_btn, R.id.chepai_time_ll, R.id.tv_selectbrand_ll, R.id.chexi_ll, R.id.chexing_ll, R.id.tv_selectAddress})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.chepai_time_ll:
                // 隐藏软键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
                yearPickerView();
                break;
            case R.id.tv_selectbrand_ll:
                Intent intent=new Intent(this,SelectCarBrandActivity.class) ;
                intent.putExtra("where",1);
                startActivityForResult(intent,001);
                break;
            case R.id.chexi_ll:
                if (pinpaiID!=0){
                    Intent intent1=new Intent(this,SelectCarBrandActivity.class);
                    intent1.putExtra("where",2);
                    intent1.putExtra("pinpaiID",pinpaiID);
                    startActivityForResult(intent1,002);
                }else {
                    ToastUtil.show(this, "请先选择品牌");
                }
                break;
            case R.id.chexing_ll:
                if (chexiID!=0){
                    Intent intent1=new Intent(this,SelectCarBrandActivity.class);
                    intent1.putExtra("where",3);
                    intent1.putExtra("chexiID",chexiID);
                    startActivityForResult(intent1,003);
                }else {
                    ToastUtil.show(this, "请先选择车系");
                }
                break;
            case R.id.bind_car_OBD_qrCode:
                Intent  intent1=new Intent(this, ScanerCodeActivity.class);
                intent1.putExtra("where","BindCarActivity");
                startActivityForResult(intent1,004);
                break;
            case R.id.bind_car_commit_btn:
                initOkGo();
                break;
            case R.id.tv_selectAddress:
                startActivity(new Intent(getApplicationContext(), SelectAddressActivity.class));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                ToastUtil.show(mContext, "扫码取消！");
            } else {
                bindCarNumberOBD.setText(result.getContents());
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }

        if (resultCode==RESULT_OK){
            if (requestCode==001){
                LogUtils.e("pinpaiID====",data.getIntExtra("pinpaiID",0)+"==========="+data.getStringExtra("pinpaiName"));
                pinpaiID=data.getIntExtra("pinpaiID",0);
                tvSelectbrand.setText(data.getStringExtra("pinpaiName"));
            }else if (requestCode==002){
                chexiID=data.getIntExtra("chexiID",0);
                chexi.setText(data.getStringExtra("chexiName"));
            }else if (requestCode==003){
                chexingID=data.getIntExtra("chexingID",0);
                chexing.setText(data.getStringExtra("chexing"));
            }else if (requestCode==004){
                bindCarNumberOBD.setText(data.getStringExtra("code"));
            }
        }

    }


    private void initQRCode(String type, String realContent) {
        if ("QR_CODE".equals(type)) {
//            Toast.makeText(getContext(), "二维码扫描结果" + realContent, Toast.LENGTH_SHORT).show();
        } else if ("EAN_13".equals(type)) {
//            Toast.makeText(getContext(), "条形码扫描结果" + realContent, Toast.LENGTH_SHORT).show();
        }

        bindCarNumberOBD.setText(realContent);
    }

    //添加车辆接口
    private void initOkGo() {
        LogUtils.e("1111111",UserBean.getcToken(mContext));
        OkGo.<String>post(Config.s + "llc/userCar/addUserCar")
                .tag(this)
                .params("token", UserBean.getcToken(mContext))
                .params("driNum", RxSPTool.getString(this, "SelectAddressTitle") + bindCarPlate.getText().toString().trim())
                .params("carDriNum", bindCarNumber.getText().toString())
                .params("motorNum", bindCarEngine.getText().toString())
                .params("registerDate", chepaiTime.getText().toString())
                .params("carBrand", tvSelectbrand.getText().toString())
                .params("carType", chexing.getText().toString())
                .params("carCate", chexi.getText().toString())
                .params("defaultCar", moren+"")
                .params("obdNum", bindCarNumberOBD.getText().toString().trim())
                .params("id", "")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean bean = gson.fromJson(response.body(), BaseBean.class);
                        if (bean.isIsSuccess()) {
                            finish();
                            Toast.makeText(BindCarActivity.this, "绑定成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(BindCarActivity.this, "" + bean.getOutputMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();
        tvSelectAddress.setText(RxSPTool.getString(this, "SelectAddressTitle"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    private void yearPickerView() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();

        //正确设置方式 原因：注意事项有说明
        startDate.set(1990, 0, 1);
        endDate.set(2050, 11, 31);


        TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {

                String Startdate = getTime(date);
                chepaiTime.setText(Startdate);

            }
        })
                .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字
                .setContentTextSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("选择时间")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setTitleColor(Color.BLACK)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.main_color))//确定按钮文字颜色
                .setCancelColor(Color.RED)//取消按钮文字颜色
                .setTitleBgColor(0xFFd6d6d6)//标题背景颜色 Night mode
                .setBgColor(0xFFffffff)//滚轮背景颜色 Night mode
                .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setLabel("年", "月", "日", "时", "分", "秒")//默认设置为年月日时分秒
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .isDialog(false)//是否显示为对话框样式
                .setBgColor(0xFFffffff)
                .build();
        pvTime.show();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


}
